package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.merchant.domain.MerchantCouponOrder;
import com.ruoyi.merchant.mapper.MerchantCouponOrderMapper;
import com.ruoyi.merchant.service.IMerchantICallbackService;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 回调Service业务层处理
 * 
 * @author dongdong
 * @date 2025-08-20
 */
@Slf4j
@Service
public class MerchantCallbackServiceImpl implements IMerchantICallbackService {

    @Autowired
    private NotificationParser notificationParser;
    @Resource
    private MerchantCouponOrderMapper merchantCouponOrderMapper;


    @Override
    public Map<String, String> wechatPayNotify(Map<String, String> headers, String body) {
        // 需要先验证签名、解密通知中的密文信息
        Map<String, String> response = new HashMap<>();
        try {
            // 1. 构造请求对象，提取微信headers
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(headers.get("wechatpay-serial"))
                    .nonce(headers.get("wechatpay-nonce"))
                    .timestamp(headers.get("wechatpay-timestamp"))
                    .signature(headers.get("wechatpay-signature"))
                    .body(body)
                    .build();

            // 2. 验签 + 解密
            Transaction transaction = notificationParser.parse(requestParam, Transaction.class);

            // 3. 拿到明文
            String tradeState = transaction.getTradeState().toString();

            switch (tradeState) {
                case "SUCCESS":
                    wechatPaymentSuccess(transaction);
                    response.put("message", "支付成功处理完成");
                    break;

                case "REFUND":
                    wechatRefund(transaction);
                    response.put("message", "退款处理完成");
                    break;

                case "CLOSED":
                    wechatOrderClosed(transaction);
                    response.put("message", "订单关闭处理完成");
                    break;

                case "PAYERROR":
                    wechatPaymentError(transaction);
                    response.put("message", "支付错误处理完成");
                    break;

                default:
                    log.error("未知的交易状态: {}", tradeState);
                    response.put("message", "未知状态已记录");
            }
            // 4. 返回成功响应（微信要求必须返回 SUCCESS，否则会反复重试）
            response.put("code", "SUCCESS");
        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", "FAIL");
            response.put("message", "处理失败: " + e.getMessage());
        }
        return response;
    }

    /**
     * 处理支付成功
     */
    private void wechatPaymentSuccess(Transaction transaction) {
        // {"amount":{"currency":"CNY","payer_currency":"CNY","payer_total":2,"total":2},"appid":"wxd027385a1c298325","attach":"","bank_type":"OTHERS","mchid":"1613441716","out_trade_no":"ORD20250826235845202","payer":{"openid":"oz6WjvsibD--FLtKMMDzWfN-1xqI"},"success_time":"2025-08-27T00:15:50+08:00","trade_state":"SUCCESS","trade_state_desc":"支付成功","trade_type":"JSAPI","transaction_id":"4200002831202508275028175492"}
        log.info("微信支付成功: 订单号={}, 金额={}, 支付时间={}",
                transaction.getOutTradeNo(),
                transaction.getAmount().getTotal(),
                transaction.getSuccessTime());
        String orderNo = transaction.getOutTradeNo();
        // 优惠券订单
        MerchantCouponOrder order = merchantCouponOrderMapper.selectMerchantCouponOrderByOrderNo(orderNo);
        Optional.ofNullable(order).orElseThrow(() -> new RuntimeException("暂未查询到订单"));
        order.setTransNo(transaction.getTransactionId());
        order.setUniqueId(transaction.getPayer().getOpenid());
        order.setOrderStatus(3);
        BigDecimal payAmount = new BigDecimal(transaction.getAmount().getTotal()).divide(new BigDecimal(100),2, RoundingMode.HALF_UP);
        order.setActualAmount(payAmount);
        order.setPayTime(DateUtils.strToLocalDateTimeUTC(transaction.getSuccessTime()));
        order.setUpdateTime(new Date());
        merchantCouponOrderMapper.updateMerchantCouponOrder(order);
    }

    /**
     * 处理退款
     */
    private void wechatRefund(Transaction transaction) {
        log.info("微信退款处理: 订单号={}", transaction.getOutTradeNo());
    }

    /**
     * 处理订单关闭
     */
    private void wechatOrderClosed(Transaction transaction) {
        log.info("微信订单关闭: 订单号={}", transaction.getOutTradeNo());
    }

    /**
     * 处理支付错误
     */
    private void wechatPaymentError(Transaction transaction) {
        log.error("微信支付错误: 订单号={}", transaction.getOutTradeNo());
    }

}
